from mtp.lib.base import *
from mtp.lib.plugin import Plugin
from mtp.lib.pageaction import PageAction
from mtp.lib.plugins.tags import TagClass
from mtp.model import Page

class PageTag(TagClass):
    object_type = 'page'


class PageTagsController(BaseController):
    def edit(self, page_id):
        c.page = Page.getByTitle(page_id)
        if not c.page: abort(404)
        
        c.pagetags = PageTag.get(c.page.id)
        return render('/pagetags/edit.html')

    def create(self, page_id):
        page = Page.getByTitle(page_id)
        if not page: abort(404)
        tags = request.params.get('tags', '').split()
        for tag in tags:
            PageTag.add(page.id, tag)
        redirect_to( h.url_for('page_edit_tags', page_id=page.urlTitle()))
        
    def delete(self, page_id, tag):
        page = Page.getByTitle(page_id)
        if not page: abort(404)
        PageTag.remove(page.id, tag)
        redirect_to( h.url_for('page_edit_tags', page_id=page.urlTitle()))

    def find(self):
        tags = [tag.strip() for tag in request.params['q'].split()
                if tag.strip()]
        
        c.tags = tags
        c.pages = PageTag.find(tags)
        return render('/pagetags/find.html')
        

class PageTagsPlugin(Plugin):
    def __init__(self, **options):
        config['mtp.controllers']['pagetags'] = PageTagsController
        #config['routes.map'].resource('pagetag', 'tags',
        #    parent_resource=dict(member_name='page', collection_name='pages'))
        map = config['routes.map']
        map.pageConnect('page_edit_tags', 'tags', 
            controller='pagetags', action='edit', conditions=dict(method=['GET']))
        map.pageConnect('page_create_tags', 'tags',
            controller='pagetags', action='create', conditions=dict(method=['POST']))
        map.pageConnect('page_delete_tags', 'tags/:tag',
            controller='pagetags', action='delete', conditions=dict(method=['DELETE']))
        map.searchConnect('search_tags', 'tags',
            controller='pagetags', action='find')

        config['mtp.extra_css'].append('/pagetags/pagetags.css')
        config['mtp.content.append'][('pages', 'show')].append(self.pageContent)
        #config['mtp.internal_content'][('pages', 'edit')].append(self.editContent)
        #config['mtp.page_actions'][('pages', 'edit')].append(self.editActions)
        config['mtp.edit_page.content.append'].append(self.editContent)
        config['mtp.edit_page.processors'].append(self.editProcess)

    def pageContent(self):
        c.pagetags = PageTag.get(c.page.id)
        if c.pagetags.count():
            return mako_render('/pagetags/list_frag.html')

    def editContent(self):
        if c.page:
            c.pagetags = PageTag.get(c.page.id)
        else:
            c.pagetags = []
        return ('Tags', mako_render('/pagetags/edit.html'))

    def editProcess(self):
        i = 1
        tags = []
        while True:
            try:
                tag = request.params['tag[%d]' % i].strip()
            except KeyError:
                break
            if tag:
                tags.append(tag)
            i += 1

        old_tags = PageTag.get(c.page.id)
        for tag in old_tags:
            if tag.tag in tags:
                tags.remove(tag.tag)
                continue
            tag.delete()
        for tag in tags:
            PageTag.add(c.page.id, tag)
        log.debug('tags %s' % str(tags))
                










